package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1.检查参数信息
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE,"用户名和密码不能为空");
        }
        //2.根据用户名查询用户信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));

        //3.校验密码
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }

        String salt = adUser.getSalt();

        String s = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!s.equalsIgnoreCase(adUser.getPassword())) {
            throw new CustomException (AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误");
        }

        //4.检查状态是否有效
        if (adUser.getStatus()!=9) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }

        //5.设置登陆时间
        adUser.setLoginTime(new Date());
        updateById(adUser);

        //6.获取用户ID，获取token
        Integer userId = adUser.getId();
        long id = Long.parseLong((userId + ""));
        String token = AppJwtUtil.getToken(id);

        //7.封装用户信息和token一起返回
        AdUserVO adUserVO = new AdUserVO();

        BeanUtils.copyProperties(adUser,adUserVO);

        Map map = new HashMap<>();

        map.put("token",token);

        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }

}
